import {deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl, downImage} from '@/api/request'
import {getSign, createUpLoadFiles, compressImg} from '@/api/common'
import DateFormat from '@/plugins/format.js'

const imageConversion = require("image-conversion");

export const CommonMixin = {

    data() {
        return {
            dataCount: 0,
            pageSize: 10,
            pageNo: 1,
            tableData: [],
            acceptImg: ".png,.jpg,.jpeg",
            // 分页参数
            /* 查询条件*/
            queryParam: {},
            uploadFileData: {},
            uploadFileSize:0,
            uploadImgUrl: "/api/ac/subsistence/businessCommonService/downImage",
        }
    },
    methods: {
        searchQuery() {
            this.loadData(1);
        },
        searchReset() {
            this.queryParam = {}
            this.loadData(1);
        },
        loadData(arg) {
            if (arg == 1) {
                this.pageNo = 1;
            }
            let that = this;
            that.Loading = true;
            let param = Object.assign({}, this.queryParam);
            let url = this.url.list;
            param.pageNo = this.pageNo;
            param.pageSize = this.pageSize;
            postAction(url, param).then((res) => {
                if (res.data.errcode != 0) {
                    this.$Message.error(res.data.errmsg);
                } else {
                    that.tableData = res.data.data.results;
                    that.dataCount = res.data.data.totalRecord;
                }
            }).finally(() => {
                that.Loading = false;
            })
        },
        handleTableChange(index) {
            this.pageNo = index;
            this.loadData();
        },
        //文件上传
        // beforeUpload() {
        //     this.Loading = true;
        //     return true;
        // },

        onSuccess() {
            this.$Message.success("上传成功！");
            this.loadData(1);
        },
        onError() {
            this.$Message.error("上传失败！");
        },

        handleEdit: function (row) {
            this.$refs.modalForm.title = "编辑";
            this.$refs.modalForm.disableSubmit = false;
            this.$refs.modalForm.key = this.uuid();
            this.$refs.modalForm.edit(row);
        },
        handleAdd: function () {
            this.$refs.modalForm.title = "新增";
            this.$refs.modalForm.disableSubmit = false;
            this.$refs.modalForm.key = this.uuid();
            this.$refs.modalForm.add();
        },
        handleDetail: function (row) {
            this.$refs.modalForm.title = "详情";
            this.$refs.modalForm.disableSubmit = true;
            this.$refs.modalForm.key = this.uuid();
            this.$refs.modalForm.edit(row);
        },
        handleDelete: function (id) {
            this.$Modal.confirm({
                title: '确定删除吗？',
                onOk: () => {
                    if (!this.url.delete) {
                        this.$Message.error("请设置url.delete属性!")
                        return
                    }
                    var that = this;
                    postAction(that.url.delete, {id: id}).then((res) => {
                        if (res.data.errcode == 0) {
                            //重新计算分页问题
                            that.reCalculatePage(1);
                            that.$Message.success("删除成功！");
                        } else {
                            that.$Message.error(res.data.errmsg);
                        }
                    });
                }
            })
        },
        uuid() {
            var s = [];
            var hexDigits = '0123456789abcdef';
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = '4';
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
            s[8] = s[13] = s[18] = s[23] = '-';

            this.uuidA = s.join('');
            return this.uuidA;
        },
        reCalculatePage(count) {
            //总数量-count
            let total = this.dataCount - count;
            //获取删除后的分页数
            let currentIndex = Math.ceil(total / this.pageSize);
            if (currentIndex == 0) {
                currentIndex = 1;
            }
            //删除后的分页数<所在当前页
            if (currentIndex < this.pageNo) {
                this.handleTableChange(currentIndex);
            } else {
                this.loadData();
            }
        },
        modalFormOk() {
            // 新增/修改 成功时，重载列表
            this.loadData();
        },
        //下载模版
        exportTemplate() {
            var fileName = this.exportTemplateFileName;
            var that = this;
            downFile(this.url.exportTemplate, this.queryParam).then((res) => {
                let blob = new Blob([res.data], {
                    // type类型后端返回来的数据中会有，根据自己实际进行修改
                    type: 'application/vnd.ms-excel'
                })
                let filename = fileName + ".xls" || 'excel.xls'
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, filename)
                } else {
                    var blobURL = window.URL.createObjectURL(blob)
                    // 创建隐藏<a>标签进行下载
                    var tempLink = document.createElement('a')
                    tempLink.style.display = 'none'
                    tempLink.href = blobURL
                    tempLink.setAttribute('download', filename)
                    if (typeof tempLink.download === 'undefined') {
                        tempLink.setAttribute('target', '_blank')
                    }
                    document.body.appendChild(tempLink)
                    tempLink.click()
                    document.body.removeChild(tempLink)
                    window.URL.revokeObjectURL(blobURL)
                }
            })
        },
        exportExcel() {
            var fileName = this.exportFileName;
            var that = this;
            that.ExportLoading = true;
            downFile(this.url.exportExcel, this.queryParam).then((res) => {
                let blob = new Blob([res.data], {
                    // type类型后端返回来的数据中会有，根据自己实际进行修改
                    type: 'application/vnd.ms-excel'
                })
                let filename = fileName + ".xls" || 'excel.xls'
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, filename)
                } else {
                    var blobURL = window.URL.createObjectURL(blob)
                    // 创建隐藏<a>标签进行下载
                    var tempLink = document.createElement('a')
                    tempLink.style.display = 'none'
                    tempLink.href = blobURL
                    tempLink.setAttribute('download', filename)
                    if (typeof tempLink.download === 'undefined') {
                        tempLink.setAttribute('target', '_blank')
                    }
                    document.body.appendChild(tempLink)
                    tempLink.click()
                    document.body.removeChild(tempLink)
                    window.URL.revokeObjectURL(blobURL)
                }
                that.ExportLoading = false;
            })
        },
        //动态设置审批必填信息
        setRequired(name, ruleValidate) {
            for (let key in ruleValidate) {
                ruleValidate[key][0].required = false;
            }
            if (name.indexOf("退回") > -1) {
                ruleValidate['tpbl0006'][0].required = true;
            } else if (name.indexOf("终止") > -1) {
                ruleValidate['tpbl0007'][0].required = true;
            } else {
                for (let key in ruleValidate) {
                    if (key != "tpbl0007" && key != "tpbl0006") {
                        ruleValidate[key][0].required = true;
                    } else {
                        ruleValidate[key][0].required = false;
                    }
                }
            }
            ruleValidate['opmemo'][0].required = true;
        },
        //获取用户信息
        getUserInfor(resolve) {
            if (sessionStorage.getItem("user_infor")) {
                resolve(JSON.parse(sessionStorage.getItem("user_infor")));
            } else {
                postAction("/api/ac/subsistence/extSysUser/userInfo", {}).then((res) => {
                    if (res.data.errcode == 0) {
                        sessionStorage.setItem("user_infor", JSON.stringify(res.data.data.userInfo));
                        resolve(res.data.data.userInfo);
                    }
                })
            }
        },
        //获取系统时间
        getServerTime(resolve) {
            postAction("/api/ac/subsistence/extSysUser/serverTime", {}).then((res) => {
                if (res.data.errcode == 0) {
                    resolve(res.data.data.serverTime);
                }
            })
        },
        //分类上浮比例转百分比
        renderSsbi0006(h) {
            if (h.cellValue) {
                return h.cellValue * 100 + "%";
            }
        },
        //列表日期转换
        renderTime(h) {
            if (h.cellValue) {
                return this.DateFormat(h.cellValue, 'YYYY-MM-DD');
            }
        },
        Time1(h) {
            if (h.cellValue) {
                return this.DateFormat(h.cellValue, 'YYYY-MM');
            }
        },
        //列表时间转换
        renderDetailTime(h) {
            if (h.cellValue) {
                return this.DateFormat(h.cellValue, 'YYYY-MM-DD HH:mm:ss');
            }
        },
        renderYesOrNo(h) {
            if (h.cellValue == '1' || h.cellValue == '01') {
                return "是";
            } else if (h.cellValue == '0') {
                return "否";
            } else {
                return "";
            }
        },
        //属地区划转码
        renderAreaName(h) {
            var list = JSON.parse(sessionStorage.getItem("sys_area_list"));
            if (list) {
                return list[h.cellValue];
            }
        },
        //获取对应属地区划
        async findAreaList() {
            var list = {};
            if (!sessionStorage.getItem("sys_area_list")) {
                const {data} = await postAction('/api/ac/subsistence/ss01001Service/findAreaListAll', {}).then(result => {
                    return result;
                });
                sessionStorage.setItem("sys_area_list", JSON.stringify(data.data));
            }
            this.loadData();
        },

        async getAreaNameByCode(name) {
            var list = {};
            if (!sessionStorage.getItem("sys_area_list")) {
                const {data} = await postAction('/api/ac/subsistence/ss01001Service/findAreaListAll', {}).then(result => {
                    return result;
                });
                sessionStorage.setItem("sys_area_list", JSON.stringify(data.data));
            }
            list = JSON.parse(sessionStorage.getItem("sys_area_list"));
            return list[name];
        },

        beforeUpload(file, name, id) {
            this.Loading = true;
            this.uploadImageFileData(file, name, id);
            return false;
        },
        async uploadImageFileData(file, name, id) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
            if (!isJpgOrPng) {
                this.$Message.error('只能上传JPG或PNG格式图片!');
                return false;
            }
            // 超过1M 压缩 图片为1M
            var fileSize = file.size / 1024 / 1024
            if (fileSize > 1 && fileSize < 2) {
                // 如果图片大于1M并且小于2M 那么压缩0.5
                file = await this.imageConversion(file, 0.5);
            } else if (fileSize > 2) {
                file = await this.imageConversion(file, 0.2);
            }
            var uploadBase64 = await
                this.file2Base64(file);
            let index = uploadBase64.indexOf('base64,') + 7;
            uploadBase64 = uploadBase64.substring(index);
            var fileName = DateFormat(new Date(), 'YYYYMMDDhhmmss') + '.png';
            var filePath = 'subsistence/' + DateFormat(new Date(), 'YYYYMMDD') + '/';
            var timeStep = new Date().getTime().toString();
            let param = {
                filePath: filePath,
                fileName: fileName,
                timestamp: timeStep
            };
            //获取签名
            var signData = await
                getSign(param);
            var sign = signData.data.data.sign;
            if (fileName.length > 20) {
                fileName = fileName.substring(0, 20) + '.png';
            }
            var uploadFileData = {
                sign: sign,
                filePath: filePath,
                fileName: fileName,
                timestamp: timeStep,
                file: uploadBase64
            };
            this.uploadFileData = uploadFileData;
            postAction('/api/ac/subsistence/businessCommonService/upload', uploadFileData).then(res => {
                this.loadImg(res.data, file, name, id);
            });
            return false;
        },

        //图片压缩
        imageConversion(file, size) {
            return new Promise((resolve, reject) => {
                imageConversion.compress(file, size).then(res => {
                    file = new File([res], file.name, {type: res.type, lastModified: Date.now()});
                    resolve(file)
                })
            });
        }
        ,


        file2Base64(file) {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                let fileResult = "";
                reader.readAsDataURL(file);
                //开始转
                reader.onload = function () {
                    fileResult = reader.result;
                };
                //转 失败
                reader.onerror = function (error) {
                    reject(error);
                };
                //转 结束  咱就 resolve 出去
                reader.onloadend = function () {
                    resolve(fileResult);
                };
            });
        }
        ,
        //下载图片
        downloadImage(url, name) {//下载图片地址和图片名
            var param = new Object();
            param.url = url;
            param.fileName = name;
            downImage(this.uploadImgUrl, param).then((res) => {
                let blob = new Blob([res.data], {
                    // type类型后端返回来的数据中会有，根据自己实际进行修改
                    type: 'image/jpeg'
                });
                let filename = name || '1.png';
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, filename)
                } else {
                    const winUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.download = filename;
                    a.href = winUrl;
                    a.click();
                }
            })
        },
        //下载word
        downloadWord(url, name) {//下载图片地址和图片名
            var param = new Object();
            param.url = url;
            param.fileName = name;
            downImage(this.uploadImgUrl, param).then((res) => {
                let blob = new Blob([res.data], {
                    // type类型后端返回来的数据中会有，根据自己实际进行修改
                    type: 'application/msword'
                });
                let filename = name || '1.docx';
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, filename)
                } else {
                    const winUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.download = filename;
                    a.href = winUrl;
                    a.click();
                }
            })
        },
        //添加验证
        fieldsToValidateAdd(names) {
            for (var i in names) {
                this.fieldsToValidate.push(names[i]);
            }
        },
        //移除验证
        fieldsToValidateRemove(names) {
            for (var i in names) {
                var index = this.fieldsToValidate.indexOf(names[i]);
                if (index >= 0) {
                    this.fieldsToValidate.splice(this.fieldsToValidate.indexOf(names[i]), 1);
                }
            }
        },
        //清除必填红框
        removeErrorCheck(names) {
            for (var i in names) {
                this.$refs['model'].fields.forEach(function (field) {
                    if (field.prop == names[i] && !this.model[names[i]]) {
                        field.resetField();
                    }
                }.bind(this));
            }
        },
        //设置必填信息
        setRequired2(fieldsToValidate) {
            var ruleValidate = this.ruleValidate;
            for (let key in ruleValidate) {
                this.$set(this.ruleValidate, key, [{}]);
            }
            var rule = this.rule;
            for (var i in fieldsToValidate) {
                this.$set(this.ruleValidate, fieldsToValidate[i], rule[fieldsToValidate[i]][0])
            }
        },
        //判断空值
        isEmpty(obj) {
            if (obj == '' || obj == null || typeof (obj) == 'undefined') {
                return true;
            } else {
                return false;
            }
        },
        //清空对象属性值
        clearPropertyValue(obj){
            Object.keys(obj).forEach(key => (obj[key] = null));
        }
    }
}
